<script setup>
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { sensorApi, warnruleApi, warnruleById } from '@T2/service/api.ts';
import { useCurrentWatchStore } from '@T2/store/users.ts';
import { distributeAIntoB, isJSON, deepCopy } from '@T2/utils/utils.ts';

const currentWatchStore = useCurrentWatchStore();
const { curProject } = currentWatchStore;

const props = defineProps({
  device: {
    type: [null, Object],
    required: true,
  },
});
const emits = defineEmits(['closed']);

const Resd = reactive({
  show: false,
});
watch(() => props.device, async (nv, ov) => {
  Resd.show = nv ? true : false;
  if (!nv) {
    sensors.current = {};
    return;
  }
  sensors.data = await getSensors(nv.id);
  const rules = await getWarnrules(nv.id);
  if (sensors.data.length) {
    distributeAIntoB(rules, sensors.data, 'sensor');
    sensors.current = sensors.data[0];
  }
});

/* 变量列表 */
const sensors = reactive({
  data: [],
  current: {},
});
const getSensors = (deviceID) => {
  return new Promise((resolve, reject) => {
    sensorApi({
      method: 'get',
      params: {
        page: 1,
        device__unit: props.device.unit,
        device: deviceID,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject(err);
    });
  })
}
const getWarnrules = (deviceID) => {
  return new Promise((resolve, reject) => {
    warnruleApi({
      method: 'get',
      params: {
        page: 1,
        device: deviceID,
        unit: props.device.unit,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject(err);
    });
  })
}
const handleSensorChange = (sensor) => {
  sensors.current = sensor;
}
watch(() => sensors.current.id, (nv, ov) => {
  setRuleForm(sensors.current?.children || []);
});

/* 报警规则 */
const ruleForm = reactive({
  currentID: null,
  type: '',
  model: {},
  rule: [],
  channel: [],
  datatypes: {},
  isChanged: false,
});
const ruleFormRef = ref(null);
const setRuleForm = (lists) => {
  ruleForm.rule = [];
  ruleForm.channel = [];
  ruleForm.datatypes = {};
  ruleForm.isChanged = false;
  setTimeout(() => {
    ruleFormRef.value.clearValidate();
  }, 50);
  if (sensors.current.datatype === '状态型') {
    if (!isJSON(sensors.current.datatype_json)) {
      ElMessage.error('变量解析配置错误！')
      return;
    }
    const oldObj = JSON.parse(sensors.current.datatype_json);
    const newObj = {};
    for (const key in oldObj) {
      if (oldObj[key]) {
        newObj[key] = oldObj[key];
      }
    }
    ruleForm.datatypes = newObj;
  }
  if (!lists.length) {
    ruleForm.currentID = null;
    ruleForm.type = 'add';
    ruleForm.model = {};
    return;
  }
  
  ruleForm.currentID = lists[0].id;
  ruleForm.type = 'edit';
  const obj = deepCopy(lists[0]);
  ruleForm.model = {
    id: obj.id,
    ruletype: obj.ruletype,
  };
  if (isJSON(obj.rule)) {
    ruleForm.rule = JSON.parse(obj.rule);
  }
  ['issystem', 'isgzh', 'shortmessage', 'email', 'voice'].forEach(i => {
    if (obj[i]) {
      ruleForm.channel.push(i);
    }
  });
}


const handleClosed = () => {
  emits('closed');
}
const submitLoading = ref(false);
const handleSubmit = async () => {
  const valid = await ruleFormRef.value.validate();
  if (!valid) {
    return;
  }
  let flag = false;
  ruleForm.rule.forEach(item => {
    if (!item.rule || !item.value || !item.level || !item.info) {
      flag = true;
      return;
    }
  });
  if (flag) {
    ElMessage.error('触发规则未补充完整！');
    return;
  }
  submitLoading.value = true;
  ['issystem', 'isgzh', 'shortmessage', 'email', 'voice'].forEach(i => {
    ruleForm.model[i] = ruleForm.channel.includes(i);
  });
  if (ruleForm.type === 'add') {
    await warnruleApi({
      method: 'post',
      data: {
        ...ruleForm.model,
        rule: JSON.stringify(ruleForm.rule),
        project: curProject.id,
        unit: props.device.unit,
        device: props.device.id,
        sensor: sensors.current.id,
        push: 0,
        level: '一',
        up: false,
      }
    });
  } else if (ruleForm.type === 'edit') {
    await warnruleById({
      method: 'patch',
      id: ruleForm.model.id,
      data: {
        ...ruleForm.model,
        rule: JSON.stringify(ruleForm.rule),
      }
    });
  }
  
  /* 初始化 */
  sensors.data.forEach(i => i.children = []);
  const rules = await getWarnrules(props.device.id);
  distributeAIntoB(rules, sensors.data, 'sensor');
  const tempID = sensors.current.id;
  sensors.current = {};
  nextTick(() => {
    sensors.current = sensors.data.find(i => i.id === tempID);
  });
  submitLoading.value = false;
}
</script>

<template>
  <div>
    <el-dialog
      v-model="Resd.show"
      :title="`参数告警配置：${ props.device?.name }`"
      :show-close="false"
      width="1025px"
      @close="handleClosed()"
    >
      <div class="sensor-box scroller-aside flex-column">
        <template v-for="(sensor, sendex) in sensors.data">
          <div class="sensor-item flex--center" :class="{ 'isActive': sensors.current.id === sensor.id}" @click="handleSensorChange(sensor)">
            <span>{{ sendex + 1 }}</span>
            <div class="sen-name ellipsis">{{ sensor.name?.replace(`${ props.device?.name }`, '') }}</div>
            <button class="highlight" v-if="sensor.children?.length">已配置</button>
            <button v-else>未配置</button>
          </div>
        </template>
        <p style="width: 100%; text-align: center; color: #ff0000;" v-if="!sensors.data.length">未查询到该设备变量</p>
      </div>
      
      <div class="right flex-column flex-sb">
        <div class="warnrule-box flex-column">
          <el-tabs v-model="ruleForm.currentID" class="warnrule-tabs" v-if="sensors.current.children?.length">
            <el-tab-pane
              v-for="(item, index) in sensors.current.children"
              :label="`规则${ index + 1 }`"
              :name="item.id"
            />
          </el-tabs>
          <div class="rule-container">
            <el-form
              ref="ruleFormRef"
              :model="ruleForm.model"
              class="flex flex-wrap"
            >
              <div class="strong-name">基础信息</div>
              <el-form-item style="width: 250px;" prop="ruletype" label="报警类型：" :rules="[{required: true, message: '不能为空', trigger: 'change'},]">
                <el-select v-model="ruleForm.model.ruletype" @change="ruleForm.isChanged = true">
                  <el-option value="设备故障" label="设备故障"></el-option>
                  <el-option value="工艺异常" label="工艺异常"></el-option>
                  <el-option value="系统故障" label="系统故障"></el-option>
                  <el-option value="通信故障" label="通信故障"></el-option>
                  <el-option value="其他故障" label="其他故障"></el-option>
                </el-select>
              </el-form-item>
              <div class="rule-lists scroller-aside">
                <div class="strong-name flex-sb-center">
                  <span>触发规则</span>
                  <el-button type="primary" link @click="ruleForm.rule.push({})">+ 新增规则</el-button>
                </div>
                <div class="rule-item flex--center" v-for="(item, index) in ruleForm.rule">
                  <label class="necessary">规则</label>
                  <el-select style="width: 120px;" v-model="item.rule" placeholder="条件" @change="ruleForm.isChanged = true">
                    <template v-if="sensors.current.datatype === '数值型'">
                      <el-option value=">=" label="大于等于 (>=)"></el-option>
                      <el-option value=">" label="大于 (>)"></el-option>
                      <el-option value="<=" label="小于等于 (<=)"></el-option>
                      <el-option value="<" label="小于 (<)"></el-option>
                    </template>
                    <el-option value="==" label="等于 (==)"></el-option>
                    <el-option value="!=" label="不等于 (!=)"></el-option>
                  </el-select>
                  &nbsp;
                  <el-input
                    v-if="sensors.current.datatype === '数值型'"
                    style="width: 100px;"
                    v-model="item.value"
                    placeholder="参考值"
                    @change="ruleForm.isChanged = true"
                  />
                  <el-select v-model="item.value" style="width: 100px;" placeholder="参考值" @change="ruleForm.isChanged = true" v-else>
                    <el-option
                      v-for="(key, index) in ruleForm.datatypes"
                      :key="index"
                      :value="key"
                      :label="key"
                    />
                  </el-select>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <label class="necessary">等级</label>
                  <el-select style="width: 80px;" v-model="item.level" placeholder="等级" @change="ruleForm.isChanged = true">
                    <el-option value="一" label="一级"></el-option>
                    <el-option value="二" label="二级"></el-option>
                    <el-option value="三" label="三级"></el-option>
                    <el-option value="四" label="四级"></el-option>
                  </el-select>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <el-input style="width: 220px;" v-model="item.info" placeholder="请输入报警文本" @change="ruleForm.isChanged = true"></el-input>
                  
                  <el-button style="margin-left: 20px;" link @click="ruleForm.rule.splice(index, 1);ruleForm.isChanged = true">
                    <el-icon size="18" color="#ff0000"><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
              
              <div class="strong-name">报警配置</div>
              <el-form-item style="width: 100%;" prop="_channel" label="通知渠道：">
                <!-- <el-select v-model="ruleForm.channel" multiple @change="ruleForm.isChanged = true">
                  <el-option value="issystem" label="系统提示"></el-option>
                  <el-option value="isgzh" label="公众号"></el-option>
                  <el-option value="shortmessage" label="短信"></el-option>
                  <el-option value="email" label="邮件"></el-option>
                  <el-option value="voice" label="语音"></el-option>
                </el-select> -->
                <el-checkbox-group v-model="ruleForm.channel" @change="ruleForm.isChanged = true">
                  <el-checkbox label="系统提示" value="issystem" border></el-checkbox>
                  <el-checkbox label="公众号" value="isgzh" border></el-checkbox>
                  <el-checkbox label="短信" value="shortmessage" border disabled></el-checkbox>
                  <el-checkbox label="邮件" value="email" border disabled></el-checkbox>
                  <el-checkbox label="语音" value="voice" border disabled></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <div class="footer flex-end">
          <el-button @click="handleClosed()">关 闭</el-button>
          <el-button
            v-if="sensors.current"
            type="primary"
            @click="handleSubmit()"
            :loading="submitLoading"
            v-prevent-rapid-click
            :disabled="!ruleForm.isChanged"
          >
            提 交
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.sensor-box {
  width: 270px;
  height: 450px;
  border: 1px solid #F5F5F5;
  padding: 16px 16px 16px 8px;
  overflow: auto;
  margin-bottom: 5px;
  .sensor-item {
    font-weight: 400;
    font-size: 14px;
    color: #111111;
    height: 40px;
    cursor: pointer;
    margin: 2px 0;
    span {
      min-width: 20px;
      margin-left: 8px;
    }
    .sen-name {
      flex: 1;
      margin-left: 10px;
    }
    &.isActive {
      color: #0079FE;
      background-color: rgba(0,121,254,0.05);
    }
    button {
      margin-left: auto;
      margin-right: 8px;
      width: 52px;
      height: 24px;
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #DCDCDC;
      background-color: transparent;
      font-weight: 400;
      font-size: 12px;
      color: #888888;
      &.highlight {
        color: #38B865;
        border-color: #38B865;
      }
    }
  }
}
.right {
  width: 755px;
  border: 1px solid #F5F5F5;
}
.warnrule-box {
  .strong-name {
    font-weight: 600;
    font-size: 14px;
    color: #111111;
    margin: 12px 0;
    width: 100%;
  }
  .rule-container {
    padding: 0 12px;
  }
  .rule-lists {
    background: #F5F5F5;
    border-radius: 8px;
    width: 100%;
    min-height: 50px;
    padding: 12px;
    max-height: 420px;
    overflow: auto;
  }
  .rule-item {
    margin-bottom: 16px;
  }
  label.necessary {
    font-weight: 400;
    font-size: 14px;
    color: #888888;
    position: relative;
    margin-left: 6px;
    margin-right: 8px;
    &::before {
      content: '*';
      position: absolute;
      left: -6px;
      top: 0;
      color: #ff0000;
    }
  }
}
.footer {
  border-top: 1px solid #F5F5F5;
  padding: 16px;
}
</style>
<style scoped>
:deep(.el-dialog) {
  padding: 0;
}
:deep(.el-dialog__header) {
  padding: 16px;
}
:deep(.el-dialog__body) {
  padding: 0;
  display: flex;
}
:deep(.el-dialog__footer) {
  display: none;
}
:deep(.warnrule-tabs .el-tabs__header) {
  margin: 0;
}
:deep(.warnrule-tabs .el-tabs__nav-wrap) {
  padding-left: 10px;
}
</style>